package com.hu.controller;

import com.hu.dal.jdbc.UserDao;
import com.hu.dal.pojo.User;
import com.hu.uitl.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "tologin", method = RequestMethod.GET)
    public ModelAndView tologin() {
        ModelAndView model = new ModelAndView();
        model.addObject("user", new User());
        model.setViewName("user/login");
        return model;
    }

    @RequestMapping(value = "dologin", method = RequestMethod.POST)
    public ModelAndView dologin(@Valid User users) {
        ModelAndView model = new ModelAndView();
        //假装从数据库里查的
        User u = new User();
        u.setId(1);
        u.setName("abc");
        u.setRole(1);
        u.setPassword("123");
        //验证
        if (!u.getName().equals(users.getName()) || !u.getPassword().equals(users.getPassword())) {
            model.setViewName("user/login");
            return model;
        }

        Map m = new HashMap<>();
        m.put("username", "abc");
        m.put("role", 1);
        m.put("id",1);
        //验证通过将用户信息生成token，并返回，同时更新到redis中，后续接口访问只需要验证token
        model.addObject("token", new JwtUtils().createToken(m));
        model.addObject("user", u);
        model.setViewName("user/index");
        return model;
    }

}
